package service

import (
	"github.com/jinzhu/gorm"
	"note.zhiwangyunchuang.com/common"
	"note.zhiwangyunchuang.com/model"
	"note.zhiwangyunchuang.com/utils"
)

func GetNoteInfoById(id int) (model.Note, string) {
	var note model.Note
	Db := common.GetDb()
	idExists := checkExistsById(id)
	if !idExists {
		return note, "数据不存在"
	}
	Db.Where("id = ?", id).First(&note)
	return note, ""
}

func AddOneNote(noteReq model.Note) (insertId uint, err string) {
	Db := common.GetDb()
	titleExists := checkExistsByTitle(noteReq.Title, 0)
	if titleExists {
		return 0, "标题重复，请重试"
	}
	Db.Create(&noteReq)
	if Db.Error != nil {
		return 0, "增加失败"
	} else {
		return noteReq.ID, ""
	}
}

func EditNoteById(id int, noteReq model.Note) (res bool, err string) {
	var note model.Note
	Db := common.GetDb()
	idExists := checkExistsById(id)
	if !idExists {
		return false, "数据不存在"
	}
	titleExists := checkExistsByTitle(noteReq.Title, id)
	if titleExists {
		return false, "名称重复，请重试"
	}
	Db.First(&note, id)
	Db.Model(&note).Updates(model.Note{
		Model:   gorm.Model{},
		Title:   noteReq.Title,
		Content: noteReq.Content,
		UserId:  noteReq.UserId,
		Type:    noteReq.Type,
	})
	if Db.Error != nil {
		return false, "信息修改失败"
	} else {
		return true, ""
	}
}

func DeleteNoteById(id int) (res bool, err string) {
	Db := common.GetDb()
	var note model.Note
	idExists := checkExistsById(id)
	if !idExists {
		return false, "信息不存在"
	}
	Db.First(&note, id)
	Db.Delete(&note, id)
	if Db.Error != nil {
		return false, "数据修改失败"
	}
	return true, ""
}

func GetNoteList() []model.Note {
	noteList := []model.Note{}
	Db := common.GetDb()
	Db.Where("id > 0").Find(&noteList)
	return noteList
}

func checkExistsById(id int) bool {
	Db := common.GetDb()
	var note model.Note
	Db.First(&note, id)
	if note.ID != 0 {
		return true
	}
	return false
}

func checkExistsByTitle(title string, id int) bool {
	Db := common.GetDb()
	var note model.Note
	Db.First(&note, "title = ? and id != ?", title, id)
	if note.ID != 0 {
		return true
	}
	return false
}

func IdentifyAudio(filePath string) string {
	content := utils.OssIdentify(filePath)
	return content
}
